const mysql = require('mysql2/promise')
const fs = require('fs')
const path = require('path')

// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '3306'),
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '123456',
  database: process.env.DB_NAME || 'my_blog',
  charset: 'utf8mb4',
  timezone: '+08:00',
  connectionLimit: 10,
  // 移除连接级别的无效配置
  // acquireTimeout: 60000,
  // timeout: 60000,
  // reconnect: true
}

async function initDatabase() {
  try {
    console.log('🚀 开始初始化数据库...')
    
    // 创建连接池
    const pool = mysql.createPool(dbConfig)
    
    // 测试连接
    const connection = await pool.getConnection()
    console.log('✅ 数据库连接成功')
    connection.release()
    
    // 读取 SQL 文件
    const sqlPath = path.join(process.cwd(), 'src', 'data', 'data.sql')
    const sqlContent = fs.readFileSync(sqlPath, 'utf-8')
    
    // 分割 SQL 语句
    const statements = sqlContent
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0)
    
    // 执行每个 SQL 语句
    for (const statement of statements) {
      console.log(`Executing SQL: ${statement}`)
      if (statement) {
        try {
          await pool.execute(statement)
          console.log('✅ 执行成功:', statement.substring(0, 50) + '...')
        } catch (error) {
          console.error('❌ 执行失败:', statement.substring(0, 50) + '...', error.message)
        }
      }
    }
    
    await pool.end()
    console.log('🎉 数据库初始化完成！')
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error.message)
    process.exit(1)
  }
}

// 运行初始化
initDatabase() 